import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Button, message, Form, Input, Modal, InputNumber, Badge, Select, Divider, Table } from 'antd';
import moment from 'moment';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './list.less';
import information from '../../utils/message';
import { dateFtt } from "../../utils/utils";

const statusMap = ['default', 'processing', 'success', 'error'];
const status = ['下架', '上架'];

const ButtonGroup = Button.Group;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const Option = Select.Option;

const CreateForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, combinationBer, loading, dataQuery, memberData,
        showInventory, cancelInventory, GarlTable, newRows, handleSelectRows,
        handleStandardTableChange, searchFormTable, newInventory, delInventory,
    } = props;
    const datafall = {
        loading,
        dataQuery,
        memberData,
        showInventory,
        cancelInventory,
        GarlTable,
        handleSelectRows,
        handleStandardTableChange,
        searchFormTable,
        newRows,
        addDate: combinationBer.productList,
    };
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            const arrsy = [];
            if (combinationBer.productList.length <= 0) {
                message.error('请至少选择一个商品');
                return;
            }
            combinationBer.productList.forEach(item => arrsy.push(item.id));
            prime.productIds = arrsy.join(',');
            form.resetFields();
            handleAdd(prime, combinationBer.id);
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };

    const columns = [
        {
            title: 'Id',
            dataIndex: 'id',
        },
        {
            title: '产品编号',
            dataIndex: 'code',
        },
        {
            title: '产品名字',
            dataIndex: 'name',
        },
        {
            title: '成本价格',
            dataIndex: 'costPrice',
            render: (val) => <span>￥ {val}</span>,
        },
        {
            title: '操作',
            width: 100,
            render: (val, record) => (
                <Fragment>
                    <Button type="danger" size="small" onClick={() => delInventory(record)} >删除</Button>
                </Fragment>
            ),
        },
    ];
    return (
        <Modal
            title="编辑产品组合"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
            width={900}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 16 }}
                        label="产品组合名字"
                    >
                        {form.getFieldDecorator('mixName', {
                            rules: [{ required: true, message: '请输入产品组合名字' }],
                            initialValue: combinationBer.mixName,
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                </Col>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 16 }}
                        label="产品组合价格"
                    >
                        {form.getFieldDecorator('mixPrice', {
                            rules: [{ required: true, message: '请输入产品组合价格' }],
                            initialValue: combinationBer.mixPrice,
                        })(
                            <InputNumber
                                style={{width: '100%'}}
                                placeholder="请输入"
                                min={0}
                                formatter={value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            />
                        )}
                    </FormItem>
                </Col>
                <Col>
                    <Divider />
                    <Button style={{marginBottom: '15px'}} onClick={() => {newInventory();}}>新增商品</Button>
                    <Table columns={columns} rowKey={record => record.id} dataSource={combinationBer.productList} size="small" pagination={false} />
                </Col>
            </Row>
            <EditUser {...datafall} />
        </Modal>
    );
});

const NewForm = Form.create()((props) => {
    const { modalVisible, form, handleAdd, handleModalVisible, loading, dataQuery, memberData, addDate,
        showInventory, cancelInventory, GarlTable, newRows, handleSelectRows,
        handleStandardTableChange, searchFormTable, newInventory, delInventory,
    } = props;
    const datafall = {
        loading,
        dataQuery,
        memberData,
        showInventory,
        cancelInventory,
        GarlTable,
        handleSelectRows,
        handleStandardTableChange,
        searchFormTable,
        newRows,
        addDate,
    };
    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            const arrsy = [];
            if (addDate.length <= 0) {
                message.error('请至少选择一个商品');
                return;
            }
            addDate.forEach(item => arrsy.push(item.id));
            prime.productIds = arrsy.join(',');
            form.resetFields();
            handleAdd(prime);
        });
    };
    const canaleModal = () => {
        handleModalVisible();
        form.resetFields();
    };

    const columns = [
        {
            title: 'Id',
            dataIndex: 'id',
        },
        {
            title: '产品编号',
            dataIndex: 'code',
        },
        {
            title: '产品名字',
            dataIndex: 'name',
        },
        {
            title: '成本价格',
            dataIndex: 'costPrice',
            render: (val) => <span>￥ {val}</span>,
        },
        {
            title: '操作',
            width: 100,
            render: (val, record) => (
                <Fragment>
                    <Button type="danger" size="small" onClick={() => delInventory(record)} >删除</Button>
                </Fragment>
            ),
        },
    ];
    return (
        <Modal
            title="新增产品组合"
            visible={modalVisible}
            onOk={okHandle}
            onCancel={canaleModal}
            width={900}
        >
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 16 }}
                        label="产品组合名字"
                    >
                        {form.getFieldDecorator('mixName', {
                            rules: [{ required: true, message: '请输入产品组合名字' }],
                        })(
                            <Input placeholder="请输入" />
                        )}
                    </FormItem>
                </Col>
                <Col md={12} sm={24}>
                    <FormItem
                        labelCol={{ span: 7 }}
                        wrapperCol={{ span: 16 }}
                        label="产品组合价格"
                    >
                        {form.getFieldDecorator('mixPrice', {
                            rules: [{ required: true, message: '请输入产品组合价格' }],
                        })(
                            <InputNumber
                                style={{width: '100%'}}
                                placeholder="请输入"
                                min={0}
                                formatter={value => `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                            />
                        )}
                    </FormItem>
                </Col>
                <Col>
                    <Divider />
                    <Button style={{marginBottom: '15px'}} onClick={() => {newInventory();}}>新增商品</Button>
                    <Table columns={columns} rowKey={record => record.id} dataSource={addDate} size="small" pagination={false} />
                </Col>
            </Row>
            <EditUser {...datafall} />
        </Modal>
    );
});

const EditUser = Form.create()((props) => {
    const { form, loading, dataQuery, memberData,
        showInventory, cancelInventory, GarlTable, newRows, handleSelectRows,
        handleStandardTableChange, searchFormTable, addDate,
    } = props;

    const memberModal = (e) => {
        form.validateFields(() => {
            form.resetFields();
            cancelInventory(e);
        });
    };

    const GridTableSear = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const prime = fieldsValue;
            GarlTable(prime);
        });
    };
    
    const srr = (e) => {
        for (const item of addDate) {
            if (item.id === e.id) {
                return <Button type="primary" disabled>已选择</Button>;
            }
        }
        return <Button type="primary" onClick={() => memberData(e)}>选择</Button>;
    };

    const columnse = [
        {
            title: 'ID',
            width: 70,
            dataIndex: 'id',
        },
        {
            title: '产品编号',
            dataIndex: 'code',
        },
        {
            title: '产品名字',
            dataIndex: 'name',
        },
        {
            title: '操作',
            render: (val, record) => {
                return (
                    <Fragment>
                        <ButtonGroup >
                            {srr(record)}
                        </ButtonGroup>
                    </Fragment>
                );
            },
        },
    ];
    const GridTable = () => {
        return (
            <Row gutter={{md: 8, lg: 24, xl: 48}}>
                <Col md={10} sm={24}>
                    {form.getFieldDecorator('code')(
                        <Input style={{width: '100%'}} placeholder="请输入编号" />
                    )}
                </Col>
                <Col md={10} sm={24}>
                    {form.getFieldDecorator('name')(
                        <Input style={{width: '100%'}} placeholder="请输入名称" />
                    )}
                </Col>
                <Col md={4} sm={24}>
                    <Button icon="search" onClick={GridTableSear} />
                </Col>
            </Row>
        );
    };

    return (
        <Modal
            visible={showInventory}
            onCancel={() => memberModal(false)}
            footer={false}
            header={false}
            width="50%"
            style={{top: '80px'}}
        >
            <Card title={GridTable()}>
                <StandardTable
                    selectedRows={newRows}
                    loading={loading}
                    data={dataQuery.data}
                    columns={columnse}
                    tableSize="small"
                    onSelectRow={handleSelectRows}
                    onChange={handleStandardTableChange}
                    searchForm={searchFormTable}
                    rowKey={record => record.id}
                />
            </Card>
        </Modal>
    );
});

@connect(({ combination, loading }) => ({
    combination,
    loading: loading.models.combination,
}))
@Form.create()
export default class combination extends PureComponent {
    state = {
        loading: false,
        selectedRows: [],
        modalVisible: false,
        modalVisibleAdd: false,
        combinationBer: {},
        searchForm: {},
        dataQuery: {},
        addDate: [],
        newRows: [],
        showInventory: false,
        searchFormTable: {},
    };

    componentDidMount() {
        this.gainList(1, 10);
        this.gainQuery(1, 10);
    }

    gainList = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'combination/fetch',
            payload: {
                page,
                size,
                data,
            },
        });
    }

    gainQuery = (page, size, data) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'combination/query',
            payload: {
                page,
                size,
                data,
            },
            callback: (data) => this.setState({dataQuery: data}),
        });
    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
            combinationBer: {},
        });
    };

    combinationAdd = (flag) => {
        this.setState({
            modalVisibleAdd: !!flag,
        });
    };

    handleEdit = (fields, id) => {
        const parime = fields;
        const { dispatch } = this.props;
        dispatch({
            type: 'combination/edit',
            payload: {
                ...parime,
                id,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.combination.combination.page, this.props.combination.combination.size, this.state.searchForm);
            },
        });

        this.setState({
            modalVisible: false,
            combinationBer: {},
        });
    };

    handleAdd = (fields) => {
        const parime = fields;
        const { dispatch } = this.props;
        dispatch({
            type: 'combination/add',
            payload: {
                ...parime,
            },
            callback: (data) => {
                information(data);
                this.gainList(this.props.combination.combination.page, this.props.combination.combination.size, this.state.searchForm);
            },
        });

        this.setState({
            modalVisibleAdd: false,
        });
    };

    combinationDel = (fields) => {
        const { dispatch, combination: { combination } } = this.props;
        confirm({
            title: '删除',
            content: '确认删除本条条目?',
            okType: 'danger',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'combination/del',
                    payload: {
                        id: fields.id,
                    },
                    callback: (data) => {
                        information(data);
                        this.gainList(combination.page, combination.size, this.state.searchForm);
                    },
                });
            },
            onCancel() {
            },
        });
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    };

    handleStandardTableChange = (pagination, filters, sorter) => {
        const data = { ...pagination.searchForm };
        this.gainList(pagination.current, pagination.pageSize, data);
    };

    handleFormReset = () => {
        const { form, dispatch } = this.props;
        form.resetFields();
        this.setState({ searchForm: {} });
    };

    cancelInventory = (flag) => {
        this.setState({
            showInventory: !!flag,
        });
        this.gainQuery(1,10,{});
    };

    GarlTable = (e) => {
        this.setState({
            searchFormTable: {...e},
        });
        this.gainQuery(1,10,e);
    };

    newStandardTableChange = (pagination, filters, sorter) => {
        const data = {...pagination.searchForm};
        this.gainQuery(pagination.current, pagination.pageSize, data);
    };

    newInventory = () => {
        this.setState({
            showInventory: true,
        });
    };F

    delInventory = (e) => {
        this.setState({
            addDate: this.state.addDate.filter((_) => _.id !== e.id),
        });
    }

    delInventoryEdit = (e) => {
        this.setState({
            combinationBer: {
                ...this.state.combinationBer,
                productList: this.state.combinationBer.productList.filter((_) => _.id !== e.id),
            },
        });
    }

    memberData = (e) => {
        this.setState({
            addDate: [
                ...this.state.addDate,
                {
                    id: e.id,
                    name: e.name,
                    code: e.code,
                    costPrice: e.costPrice,
                },
            ],
            showInventory: false,
        });
        this.gainQuery(1,10,{});
    };

    memberDataEdit = (e) => {
        this.setState({
            combinationBer: {
                ...this.state.combinationBer,
                productList: [
                    ...this.state.combinationBer.productList,
                    {
                        id: e.id,
                        name: e.name,
                        code: e.code,
                        costPrice: e.costPrice,
                    },
                ],
            },
            showInventory: false,
        });
        this.gainQuery(1,10,{});
    };

    handleSearch = (e) => {
        e.preventDefault();

        const { dispatch, form } = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;
            if (fieldsValue.id && fieldsValue.id.toString().length > 10) {
                message.error('id小于等于10位');
                return;
            }
            this.setState({
                searchForm: { ...fieldsValue },
            });
            dispatch({
                type: 'combination/fetch',
                payload: {
                    page: 1,
                    size: this.props.combination.combination.size,
                    data: {
                        ...fieldsValue,
                    },
                },
            });
        });
    };

    renderBrandForm() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                    <Col md={6} sm={24}>
                        <FormItem label="组合产品ID">
                            {getFieldDecorator('id', {
                                initialValue: '',
                            })(
                                <InputNumber style={{ width: '100%' }} min={1} max={2147483647} placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="组合产品名字">
                            {getFieldDecorator('mixName', {
                                initialValue: '',
                            })(
                                <Input placeholder="请输入" />
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <FormItem label="上下架状态">
                            {getFieldDecorator('shelfStatus', {
                                initialValue: null,
                            })(
                                <Select style={{ width: '100%' }}>
                                    <Option value={null}>请选择</Option>
                                    <Option value={0}>下架</Option>
                                    <Option value={1}>上架</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={6} sm={24}>
                        <span className={styles.submitButtons} style={{ textAlign: 'right' }}>
                            <Button icon="search" htmlType="submit" />
                            <Button style={{ marginLeft: 8 }} type="dashed" onClick={this.handleFormReset}>重置</Button>
                            <Button style={{ marginLeft: 8 }} type="primary" onClick={() => {
                                this.combinationAdd(true);
                                this.setState({addDate: []});
                            }}>新增</Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    render() {
        const { selectedRows, combinationBer, modalVisible, modalVisibleAdd, dataQuery, newRows, showInventory,
            searchFormTable, addDate,
        } = this.state;
        const { combination: { combination }, loading, dispatch } = this.props;
        const parentMethods = {
            handleAdd: this.handleEdit,
            handleModalVisible: this.handleModalVisible,
            combinationBer,
            loading,
            dataQuery,
            showInventory,
            cancelInventory: this.cancelInventory,
            GarlTable: this.GarlTable,
            handleSelectRows: this.handleSelectRows,
            handleStandardTableChange: this.newStandardTableChange,
            searchFormTable,
            newRows,
            newInventory: this.newInventory,
            delInventory: this.delInventoryEdit,
            memberData: this.memberDataEdit,
        };
        const AddBrand = {
            loading,
            handleAdd: this.handleAdd,
            handleModalVisible: this.combinationAdd,
            dataQuery,
            showInventory,
            cancelInventory: this.cancelInventory,
            GarlTable: this.GarlTable,
            handleSelectRows: this.handleSelectRows,
            handleStandardTableChange: this.newStandardTableChange,
            searchFormTable,
            newRows,
            addDate,
            newInventory: this.newInventory,
            delInventory: this.delInventory,
            memberData: this.memberData,
        };
        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
            },
            {
                title: '名字',
                dataIndex: 'mixName',
            },
            {
                title: '价格',
                dataIndex: 'mixPrice',
            },
            {
                title: '使用状态',
                dataIndex: 'shelfStatus',
                render: (val, record) => {
                    const params = record;
                    const arrey = {
                        id: params.id,
                    };
                    return <a onClick={() => {
                        if (params.shelfStatus === 0) {
                            arrey.shelfStatus = 1;
                        } else {
                            arrey.shelfStatus = 0;
                        }
                        dispatch({
                            type: 'combination/edit',
                            payload: arrey,
                            callback: (datas) => {
                                information(datas);
                                this.gainList(this.props.combination.page, this.props.combination.size, this.state.searchForm);
                            },
                        });
                    }}><Badge status={statusMap[val]} text={status[val]} /></a>;
                },
            },
            {
                title: '创建日期',
                dataIndex: 'createDate',
                render: (val) => {
                    const crtTime = new Date(val);
                    return (
                        <span>{dateFtt("yyyy-MM-dd hh:mm:ss",crtTime)}</span>
                    );
                },
            },
            {
                title: '操作',
                width: 260 ,
                render: (val, record) => (
                    <Fragment>
                        <ButtonGroup>
                            <Button type="ghost" onClick={() => {
                                dispatch({
                                    type: 'combination/info',
                                    payload: {
                                        id: record.id,
                                    },
                                    callback: (data) => {
                                        this.handleModalVisible(true);
                                        this.setState({
                                            combinationBer: data.data,
                                        });
                                    },
                                });
                            }}>编辑</Button>
                            <Button type="danger" onClick={() => {
                                this.combinationDel(record);
                            }}>删除</Button>
                        </ButtonGroup>
                    </Fragment>
                ),
            },
        ];

        return (
            <PageHeaderLayout title="产品组合列表">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderBrandForm()}
                        </div>
                        <StandardTable
                            selectedRows={selectedRows}
                            loading={loading}
                            data={combination}
                            columns={columns}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleStandardTableChange}
                            searchForm={this.state.searchForm}
                        />
                    </div>
                </Card>
                <CreateForm
                    {...parentMethods}
                    modalVisible={modalVisible}
                />
                <NewForm
                    {...AddBrand}
                    modalVisible={modalVisibleAdd}
                />
            </PageHeaderLayout>
        );
    }
}
